package cn.edu.swu.io_2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;

public class FileUtils {
    /**
     * 文件工具类
     * 提供静态方法，从网页下载图片，并记录下载记录到日志中
     * */
    private FileUtils(){}
    public static void saveImage(String url, String savePath) throws IOException {
        // 从URL下载图片并保存到指定路径
        URL imageUrl = new URL(url);
        System.out.println("开始下载图片...");
        // 记录下载时间
        long start = Calendar.getInstance().getTimeInMillis();
        // 使用本工具类中的方法ensureDirectoryExists，确保路径存在
        ensureDirectoryExists(savePath);

        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024 * 4];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        // 记录下载结束时间
        long end = Calendar.getInstance().getTimeInMillis();

        System.out.println("图片下载结束！下载时间："+ (end - start) + "ms");
    }

    public static void ensureDirectoryExists(String dirPath) throws IOException{
        // 检查目录是否存在，不存在则创建
        Path path = Paths.get(dirPath);
        Path parentDir = path.getParent();

        if (parentDir != null && !Files.exists(parentDir)){
            Files.createDirectories(parentDir);
            System.out.println("创建了目录"+parentDir);
        }
    }

    public static void appendLog(String log){
        // 将下载记录写入download_log.txt（日志文件）
        try {
            String logFile = "2_java_io\\download_log.txt";
            ensureDirectoryExists(logFile);
            // 获取时间戳
            String timestamp = LocalDateTime.now().format(
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 生成一条日志字符串
            String logEntry =  timestamp  + log + "\n";

            Files.write(Paths.get(logFile), logEntry.getBytes(),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);


        } catch (IOException e) {
            System.err.println("写入日志失败: " + e.getMessage());
        }

    }




}
